//
//  BPAFNetworkingTool.swift
//  Alamofire
//
//  Created by apple on 16/4/8.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import AFNetworking

//swift 中的枚举
enum BPHttpMethods: String {
    case POST = "POST"
    case GET = "GET"
}

//MARK:定义接口名称
//因为工作中会用到很多的接口,所以我们要定义一个结构体,来存放这些接口,方便调用
struct API {
    //线上环境
    static let onlineHost = "https://api.weibo.com/"
    //测试环境
    static let devHost = "https://dev.api.weibo.com/"
    //获取用户token的接口
    static let loadToken = "oauth2/access_token"
    //获取用户数据的接口
    static let loadUserInfomation = "2/users/show.json"
    
    //获取当前登录用户及其所关注（授权）用户的最新微博
    //static let laodHomeInfomaation = "2/statuses/home_timeline.json"
    static let laodHomeInfomaation = "2/statuses/friends_timeline.json"
    //发送文字围脖的接口
    static let sendText = "2/statuses/update.json"
    //获取微博发布的图片接口
    static let uploadImage = "https://upload.api.weibo.com/2/statuses/upload.json"
}


class BPAFNetworkingTool: AFHTTPSessionManager {
    //1.声明单例对象
    static let sharedTools: BPAFNetworkingTool = {
    
        //设置baseurl
        let tools = BPAFNetworkingTool(baseURL: NSURL(string: API.onlineHost))
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    
    }()
    

}


//MARK:加载首页数据的网络请求的方法
extension BPAFNetworkingTool {
    
    ///请求首页数据的方法
    
    //当我们需要刷新加载的操作的时候需要传入两个参数,根据这两个参数来
    func loadHomeInfomation(token: AnyObject,since_id:Int64,max_id:Int64,finished:(respondData: AnyObject?,error: NSError?) -> ()) {
        
        //设置参数
        var parameters = ["access_token" : token]
        
        //判断,防止重用
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        
        //网络请求
        request(.GET, urlString: API.laodHomeInfomaation, parameters: parameters, finished: finished)
    

    }

}


//MARK:登陆和注册的网络请求的方法
extension BPAFNetworkingTool {
    
    //MARK:登录授权的请求,获取token
    func loadAccessTokenNet(code: String,finished:(respondData: AnyObject?,error: NSError?) -> ()) {
        //let urlString = "https://api.weibo.com/oauth2/access_token"
        //print(code)
        //设置参数
        let parameters = ["client_id":client_id,
            "client_secret":client_secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri]
        
        //通过我们封装的网络请求的工具类来获取数据
        request(.POST, urlString: API.loadToken, parameters: parameters, finished: finished)
    
    }
    
    
    //MARK:通过token获取具体用户信息的方法
    func loadUserInfomation(token:AnyObject,uid:AnyObject,finished:(respondData: AnyObject?,error: NSError?) -> ()) {
        //获取用户接口信息的URL
        //let userStr = "https://api.weibo.com/2/users/show.json"
        
        //设置参数数组
        let parameters = ["access_token" : token,"uid" : uid]
    
    
        //调用核心方法
        request(.GET, urlString: API.loadUserInfomation, parameters: parameters, finished: finished)
    }
    
}

//MARK:发送微博的网络请求
extension BPAFNetworkingTool {
    
    func sendWeiBo(access_token:String,status:String,imgList:[UIImage] = [UIImage](),finished:(respondData: AnyObject?,error: NSError?) -> ()) {
        //设置参数数组
        let parameters = ["access_token" : access_token,"status" : status]
        //发布图片微博
        if imgList.count > 0 {
        
            //AFN
            POST(API.uploadImage, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
                /**
                 *将要上传的二进制数据添加到formdata
                 *
                 *  @param data  要上传的二进制数据
                 *  @param name  服务器接收上传文件的字段名
                 *  @param fileName  服务器获取到文件之后 以什么名称存储  名字可以随便取,新浪微博会按照自己的命名规则命名
                 *  @param mimeType   文件类型
                 *
                 *  @return
                 */
                for (index,image) in imgList.enumerate() {
                    let imageData = UIImagePNGRepresentation(image)!
                    formdata.appendPartWithFileData(imageData, name: "pic", fileName: "xxxxxx\(index)", mimeType: "image/jpeg")
                }
                }, progress: nil , success: { (_, respondData) ->Void in
                    finished(respondData: respondData, error: nil)
                }, failure: { (_, error) -> Void in
                    finished(respondData: nil, error: error)
            })
        }else {
        request(.POST, urlString: API.sendText, parameters: parameters, finished: finished)
        }
    
    }
}



//MARK:封装所有的网络请求的方法,也就是网络的核心方法
extension BPAFNetworkingTool {

    func request(method: BPHttpMethods,urlString: String,parameters: AnyObject?,finished:(respondData: AnyObject?,error: NSError?) -> ()) {
        
        //swift中不能够利用协议欺骗Xcode,为了达到封装的目的,只能将相同的闭包抽取出来,当做参数传递给AFN框架
        
        //2.定义成功的回调
        let sussces = { (task: NSURLSessionDataTask,result: AnyObject?) -> Void in
            
            //2.1执行成功的回调
            finished(respondData: result, error: nil)
            
        }
        
        //3.定义失败的回调
        let failure = { (task: NSURLSessionDataTask?,error: NSError) -> Void in
            //3.1执行失败的回调
            finished(respondData: nil, error: error)
            
        }
        
        //4.判断使用哪种请求方法
        if method == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: sussces, failure: failure)
        }else {
            POST(urlString, parameters: parameters, progress: nil, success: sussces, failure: failure)
        }
        
    }

}

